/**
 * 文件上传工具
 */
import { request } from "./request"

/**
 * 上传文件
 * @param {string} url - 上传地址
 * @param {File} file - 文件对象
 * @param {Function} onProgress - 上传进度回调
 * @returns {Promise}
 */
export function uploadFile(url, file, onProgress) {
  const formData = new FormData()
  formData.append('file', file)

  return request.post(url, formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    onUploadProgress: (event) => {
      if (onProgress) {
        const percent = Math.round((event.loaded * 100) / event.total)
        onProgress(percent)
      }
    }
  })
}

/**
 * 下载文件
 * @param {string} url - 下载地址
 * @param {string} filename - 文件名
 * @returns {Promise}
 */
export async function downloadFile(url, filename) {
  const response = await request.get(url, {
    responseType: 'blob'
  })

  // 创建下载链接
  const blob = new Blob([response.data])
  const downloadUrl = window.URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = downloadUrl
  link.download = filename
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  window.URL.revokeObjectURL(downloadUrl)

  return response
}
